<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Admins extends CI_Controller
{
	private $token_user, $admin_id;
	public function __construct()
	{
		parent::__construct();
		$this->token_user = check_token();
		$this->admin_id = $this->token_user[0];
		$this->load->model(array('admin_model', 'admin_group_model'));
	}


	public function pwd()
	{
		//权限检查
		if (!$this->admin_group_model->check_perm('admins_pwd', $this->token_user[3])) {
			response_json([], 101, '权限错误，请联系管理员');
		}
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$login_pwd = $this->input->get_post('login_pwd');
			$admin_pwd = $this->input->get_post('admin_pwd');
			$again_admin_pwd = $this->input->get_post('again_admin_pwd');
			$row       = $this->admin_model->get_by_id($this->admin_id);

			if (empty($login_pwd)) {
				response_json([], '101', '请输入当前登录密码!');
			}

			if (md5(md5($login_pwd) . $row['admin_salt']) != $row['admin_pwd']) {
				response_json([], '101', '当前登录密码错误!');
			}

			if (empty($admin_pwd)) {
				response_json([], '101', '请输入新的密码!');
			}

			if ($admin_pwd != $again_admin_pwd) {
				response_json([], '101', '两次输入密码不一致!');
			}

			$admin_salt = randomstr(6);
			$admin_pwd  = md5(md5($admin_pwd) . $admin_salt);
			$update     = array();
			$update['admin_salt'] = $admin_salt;
			$update['admin_pwd']  = $admin_pwd;

			$this->admin_model->update($row['admin_id'], $update);
			response_json([], '1001', '您的密码已经修改!');
		}
	}

	public function groupList()
	{
		response_json($this->admin_group_model->result_maps($this->admin_group_model->result_all()));
	}

	public function group()
	{
        //权限检查
        if(!$this->admin_group_model->check_perm('admins_group',$this->token_user[3]))
        {
            response_json([],101,'权限错误，请联系管理员');
        }
        $opt = $this->input->get_post('opt');

		$groups = $this->admin_group_model->result_maps($this->admin_group_model->result_all());

		if ($opt == 'edit') {
			$id = (int) $this->input->get_post('id');
			if (!isset($groups[$id])) {
                response_json([],'101',"参数错误!");
			}

			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				$group_name = $this->input->get_post('group_name');
				$group_perm = (array) $this->input->get_post('group_perm');

				if (empty($group_name)) {
                    response_json([],'101',"请填写分组名称!");
				}
				if (empty($group_perm)) {
                    response_json([],'101',"请选择分组权限!");
				}

				$update = array(
					'group_name' => $group_name,
					'group_perm' => json_encode($group_perm),
				);

				$this->admin_group_model->update($id, $update);
                response_json();
			}
		}

		if ($opt == 'add') {

			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				$group_name = $this->input->get_post('group_name');
				$group_perm = (array) $this->input->get_post('group_perm');

				if (empty($group_name)) {
                    response_json([],'101',"请填写分组名称!");
				}
				if (empty($group_perm)) {
                    response_json([],'101',"请选择分组权限!");
				}

				$insert = array(
					'group_name' => $group_name,
					'group_perm' => json_encode($group_perm),
				);

				$this->admin_group_model->insert($insert);
                response_json();
			}
		}
        if($opt == 'del')
        {
            $id   = (integer)$this->input->get_post('id');
            $info = $this->admin_group_model->get_by_id($id);
            if(empty($info))
            {
                response_json([],'101',"参数错误!");
            }
            // 查找版块下是否存用户。
            $child = $this->admin_model->get_by_where('group_id='.$id.' and status != -1');
            if(!empty($child)){
                response_json([],'101',"存在用户，无法删除!");
            }
            $this->admin_group_model->delete($id);
            response_json();
        }

        $total      = count($groups);
        if($total > 0){
            $_data['code'] = 0;
            $_data['msg'] = 'ok';
        }else{
            $_data['code'] = 101;
            $_data['msg'] = '无数据';
        }
        $_data['data'] = $groups;
        $_data['count'] = $total;

        echo json_encode($_data);
	}
	public function group_info(){
        $id   = (integer)$this->input->get_post('id');
        $info = $this->admin_group_model->get_by_id($id);
        if(empty($info))
        {
            response_json([],'101',"参数错误!");
        }
        $groups = $this->admin_group_model->result_maps($this->admin_group_model->result_all());
        $groups[$id]['group_perm'] = json_decode($groups[$id]['group_perm'], true);
        $data   = array(
            'info' => $groups[$id]
        );
        response_json($data);
    }


	public function add()
	{
        //权限检查
        if(!$this->admin_group_model->check_perm('admins_add',$this->token_user[3]))
        {
            response_json([],101,'权限错误，请联系管理员');
        }
		if ($_SERVER['REQUEST_METHOD'] == 'POST') {
			$admin_name = $this->input->get_post('admin_name');
			if (empty($admin_name)) {
                response_json([],'101',"请填写登录帐号!");
			}
			$admin_pwd  = $this->input->get_post('admin_pwd');
			if (empty($admin_pwd)) {
                response_json([],'101',"请填写登录密码!");
			}
			$group_id = (int) $this->input->get_post('group_id');
            $groups = $this->admin_group_model->result_maps($this->admin_group_model->result_all());
			if (!isset($groups[$group_id])) {
                response_json([],'101',"请选择正确的管理组!");
			}
			$check_name = $this->admin_model->get_by_where(array('admin_name' => $admin_name));
			if ($check_name && $check_name['status'] <> -1) {
                response_json([],'101',"登录帐号已被使用!");
			}

			$admin_salt = randomstr(6);
			$admin_pwd  = md5(md5($admin_pwd) . $admin_salt);

			$insert = array(
				'admin_name' => $admin_name,
				'admin_salt' => $admin_salt,
				'admin_pwd'  => $admin_pwd,
				'group_id'   => $group_id,
				'regtime'    => date('Y-m-d H:i:s'),
				'regip'      => getip(),
			);

			$this->admin_model->insert($insert);
            response_json();
		}
	}

	public function index()
	{
		$opt = $this->input->get_post('opt');
        //权限检查
        if(!$this->admin_group_model->check_perm('admins_index',$this->token_user[3]))
        {
            response_json([],101,'权限错误，请联系管理员');
        }

		if ($opt == 'edit') {
			$groups     = $this->admin_group_model->result_maps($this->admin_group_model->result_all());
			$admin_id   = (int) $this->input->get_post('id');
			$admin_info = $this->admin_model->get_by_id($admin_id);
			if (empty($admin_info)) {
                response_json([],'101',"参数错误!");
			}

			if ($_SERVER['REQUEST_METHOD'] == 'POST') {
				$admin_name = $this->input->get_post('admin_name');
				if (empty($admin_name)) {
                    response_json([],'101',"请填写登录帐号!");
				}
				$check_name = $this->admin_model->get_by_where(array('admin_name' => $admin_name));
				if ($check_name && $check_name['admin_id'] != $admin_id && $check_name['status'] <> -1) {
                    response_json([],'101',"登录帐号已被使用!");
				}
				$update = array(
					'admin_name' => $admin_name
				);
				$admin_pwd = $this->input->get_post('admin_pwd');
				if ($admin_pwd) {
					$admin_salt = randomstr(6);
					$admin_pwd  = md5(md5($admin_pwd) . $admin_salt);
					$update['admin_salt'] = $admin_salt;
					$update['admin_pwd']  = $admin_pwd;
				}

				$group_id = (int) $this->input->get_post('group_id');
				if (!isset($groups[$group_id])) {
                    response_json([],'101',"请选择正确的管理组!");
				}
				$update['group_id']  = $group_id;

				$this->admin_model->update($admin_id, $update);

                response_json();
			}
		}

		if ($opt == 'status') {
			$admin_id   = (int) $this->input->get_post('id');
			$update     = array(
				'status' => intval($this->input->get_post('val')),
			);
			$this->admin_model->update($admin_id, $update);
			response_json();
		}
		$limit     = intval($this->input->get('limit')) > 0 ? $this->input->get('limit') : 20;
		$cur_page      = intval($this->input->get('page'));
		$cur_page   = $cur_page > 0 ? $cur_page : 1;
		$offset     = ($cur_page - 1) * $limit;

		$q			= (string) $this->input->get('q');

		$where      = "where `status`<>-1";

		if (!empty($q)) {
			$where  .= " and (`admin_name` like '%" . $q . "%')";
		}

		$order_by   = "order by `regtime` desc";
		$result     = $this->admin_model->result_data($where, $order_by, $offset, $limit);
		$total      = $this->admin_model->result_count($where);
		$groups     = $this->admin_group_model->result_maps($this->admin_group_model->result_all());

		$statusArr = array("-1" => "删除", "0" => "禁用", "1" => "正常");
		foreach ($result as $k => $val) {
			$val['group_name'] = $groups[$val['group_id']]["group_name"];
			$val["status_name"] = $statusArr[$val['status']];
			$result[$k]   = $val;
		}

		response_listJson($result, $total);
	}

    /**
     * 获取所有权限分类
     */
	public function perms(){
        $this->config->load('menu', true);
        $menu = $this->config->item('admin_menu', 'menu');
        response_json($menu);
    }
}
